package com.maimao.cart.controller;

import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Lists;
import com.maimao.api.mall.shopping_cart.ShoppingCartApi;
import com.maimao.cart.client.GoodsClient;
import com.maimao.cart.controller.base.BaseController;
import com.maimao.cart.service.ShoppingCartService;
import com.maimao.core.enums.RespCode;
import com.maimao.core.model.auth.AuthUser;
import com.maimao.core.model.resp.Result;
import com.maimao.model.cart.ShoppingCart;
import com.maimao.model.cart.ShoppingCartVo;
import javafx.application.Application;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.maimao.core.constant.Constants.COMMA;

/**
 * @author MaoLin Wang
 * @date 2021/1/10 10:56 上午
 */
@RestController
public class ShoppingCartController extends BaseController implements ShoppingCartApi {

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 合并离线购物车 检查sku失败的数据，返回前端保留离线数据； sku失效的，valid=false，否则valid=true
     *
     * @param shoppingCartList 待合并的购物车数据
     */
    @Override
    @PostMapping(value = "/mergeCart")
    public Result<?> mergeCart(@Valid @RequestBody List<ShoppingCart> shoppingCartList, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            String errors = bindingResult.getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.joining(COMMA));
            logger.error("合并购物车失败，字段校验错误:{}", errors);
            //不返回fail，否则前端会被拦截到弹出提示不友好，前端根据code直接处理是否清除离线数据
            return Result.ok(RespCode.MERGE_SHOPPING_CART_ERROR);
        }
        AuthUser authUser = checkAndGetAuthUser();
        List<String> failSkuId = Lists.newArrayList();
        if (ObjectUtil.isNotEmpty(shoppingCartList)) {

            Iterator<ShoppingCart> iterator = shoppingCartList.iterator();
            while (iterator.hasNext()) {
                ShoppingCart shoppingCart = iterator.next();
                shoppingCart.setUserId(Long.valueOf(authUser.getId()));
                Result<Boolean> checkSku = goodsClient.checkSku(shoppingCart.getSkuId());
                if (checkSku == null || checkSku.getData() == null) {
                    failSkuId.add(shoppingCart.getSkuId().toString());
                    iterator.remove();
                    continue;
                }
                if (!checkSku.getData()) {
                    shoppingCart.setValid(false);
                } else {
                    shoppingCart.setValid(true);
                }
            }
            shoppingCartService.mergeData(shoppingCartList);
        }
        if (ObjectUtil.isNotEmpty(failSkuId)) {
            logger.info("添加失败的购物车数据，skuId列表：{}", failSkuId);
            return Result.ok(RespCode.MERGE_SHOPPING_CART_FAIL, null, failSkuId);
        }
        return Result.ok(RespCode.OK);
    }

    /**
     * 添加购物车
     *
     * @param shoppingCart
     * @return
     */
    @Override
    @PostMapping(value = "/addCart")
    public Result<?> addCart(@Valid @RequestBody ShoppingCart shoppingCart, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return entityInvalid(bindingResult);
        }
        AuthUser authUser = checkAndGetAuthUser();
        shoppingCart.setUserId(Long.valueOf(authUser.getId()));
        Result<Boolean> checkSku = goodsClient.checkSku(shoppingCart.getSkuId());
        if (checkSku == null || checkSku.getData() == null) {
            return Result.fail("添加失败");
        }
        if (!checkSku.getData()) {
            return Result.notValid("宝贝已经下架啦！");
        }
        shoppingCart.setValid(true);
        shoppingCartService.addCart(shoppingCart);

        return Result.ok();
    }

    @GetMapping("/query-sku")
    @Override
    public Result<?> querySku(@RequestParam("skuId") Long skuId) {
        if (skuId == null || skuId <= 0) {
            return Result.notValid("暂无商品信息");
        }
        ShoppingCart shoppingCart = shoppingCartService.queryBySkuId(skuId, Long.valueOf(checkAndGetAuthUser().getId()));
        return Result.okData(shoppingCart);
    }

    /**
     * 查询当前用户的购物车列表
     */
    @Override
    @GetMapping("/shopping-cart-list")
    public Result<?> shoppingCartData() {
        AuthUser authUser = checkAndGetAuthUser();
        List<ShoppingCartVo> shoppingCartVos = shoppingCartService.shoppingCartData(Long.valueOf(authUser.getId()));
        return Result.okData(shoppingCartVos);
    }

    /**
     * 修改购物车某个商品数量
     *
     * @param shoppingCart
     * @return
     */
    @PutMapping("/update-num")
    @Override
    public Result<?> updateNum(@RequestBody ShoppingCart shoppingCart) {
        if (shoppingCart.getId() == null || shoppingCart.getId() <= 0 || shoppingCart.getNum() == null || shoppingCart.getNum() <= 0 || shoppingCart.getTotalPrice() == null || shoppingCart.getTotalPrice().longValue() < 0) {
            return Result.notValid();
        }
        shoppingCartService.updateNum(shoppingCart.getId(), shoppingCart.getNum(), shoppingCart.getTotalPrice());
        return Result.ok();
    }

    /**
     * 批量删除购物车商品
     */
    @Override
    @DeleteMapping("/delete/cart")
    public Result<?> deleteCarBatch(@RequestBody List<Long> ids) {
        if (ids == null || ids.size() <= 0) {
            return Result.notValid();
        }
        shoppingCartService.deleteCarBatch(ids);
        return Result.ok("删除成功");
    }

    /**
     * 清除当前登录用户的购物车的失效商品
     */
    @Override
    @PostMapping("/delete-invalid")
    public Result<?> removeInvalidGoods() {
        AuthUser authUser = checkAndGetAuthUser();
        shoppingCartService.removeInvalidGoods(Long.valueOf(authUser.getId()));
        return Result.okData("清除成功");
    }
}
